'''
Created on 2010/10/31

@author: yukiyonezawa
'''
from pyrfid.DataProtocol.DSFID.AFI import AFI
from pyrfid.asn1.Encoder import Encoder
from pyrfid.asn1.Decoder import Decoder
from pyrfid.DataProtocol.Exception.ExecutionCodeException.ExecutionCodeException import ExecutionCodeException
from pyrfid.DataProtocol.Exception.CompletionCodeException.AFINotConfiguredException import AFINotConfiguredException

class ConfigureAFICRU(object):
    
    def __init__(self, tag_id, command_list, driver):
        '''
        int tag_id
        ?? dsfid
        list command_list
        '''        
        print "ConfigureAFICRU"
        self.TAG_ID = tag_id
        self.command_list = command_list
        self.driver = driver
        self.complete_code = 0
        self.execution_code = 0
    
    def execute(self):
        print "ConfigureAFICRU execute"
        
        application_family = self.command_list.popElement().VALUE        
        application_subfamily = self.command_list.popElement().VALUE        
        afi_lock = self.command_list.popElement().VALUE        
        
        afi = AFI(int(application_family), int(application_subfamily))        
        try:
            self.driver.configureAFI(self.TAG_ID, afi)
        except ExecutionCodeException, e:
            self.execution_code = e.EXECUTION_CODE
            self.complete_code = AFINotConfiguredException().COMPLETION_CODE
    
    def encode(self, response_cru_id):
        encoder = Encoder()
        listRSPAndData = []
        listRSPAndData.append(['06', '05', Encoder.oidEncode(response_cru_id)])
        listRSPAndData.append([Decoder.SEQUENCE_AND_SEQUENCE_OF, '', ''])
        
        #completion code:INTEGER
        listRSPAndData.append([Decoder.INTEGER, '01', encoder.intEncode(self.complete_code) ])
        #exception code:INTEGER
        listRSPAndData.append([Decoder.INTEGER, '01', encoder.intEncode(self.execution_code)])
        
        allLength = 1 + 1
        listRSPAndData[1][1] = encoder.lengthEncode(allLength)
        
        #print 'ListRSP: '
        # for l in self.listRSPAndData:
        #             print l
        #        
        rspHex = str()
        for l in listRSPAndData:
            for s in l:
                rspHex += s
        return rspHex


    